package controller

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type SearchController struct {
	*BaseController
}

// Index 搜索文章功能
func (s *SearchController) Index(c *gin.Context) {
	keyword := c.DefaultQuery("keyword", "")
	keywordEscape := s.ReplaceSpecifiedChar(keyword)
	fmt.Printf("%s\n", keywordEscape)
	p := c.DefaultQuery("page", "1")

	page, _ := strconv.ParseInt(p, 10, 64)

	// 获取文章
	pageResult := articleModel.GetArticlePage(page, 10, keywordEscape, "", "", "")
	pageResult["keyword"] = keyword
	pageResult["tag"] = ""

	pageCount := pageResult["pageCount"]
	pc, err := strconv.ParseInt(fmt.Sprintf("%v", pageCount), 10, 64)
	if err != nil {
		fmt.Printf("%d\n", pc)
	}
	var pageHtml []map[string]string
	for i := 0; i < int(pc); i++ {
		if len(pageHtml) >= 5 {
			break
		}
		pageIndex := fmt.Sprintf("%d", i+1)
		ph := map[string]string{
			"url":       "/search?keyword=" + keyword + "&page=" + pageIndex,
			"pageIndex": pageIndex,
		}
		pageHtml = append(pageHtml, ph)
	}

	pageResult["pageHtml"] = pageHtml

	// 下一分页
	nextPage := page + 1
	if page == pc {
		pageResult["nextPage"] = page
		pageResult["nextPageUrl"] = fmt.Sprintf("/search?keyword=%s&page=%d", keyword, page)
	} else {
		pageResult["nextPage"] = nextPage
		pageResult["nextPageUrl"] = fmt.Sprintf("/search?keyword=%s&page=%d", keyword, nextPage)
	}

	if page > 1 {
		pageResult["prevPage"] = page - 1
		pageResult["prevPageUrl"] = fmt.Sprintf("/search?keyword=%s&page=%d", keyword, page-1)
	} else {
		pageResult["prevPage"] = page
		pageResult["prevPageUrl"] = fmt.Sprintf("/search?keyword=%s&page=%d", keyword, page)
	}

	tags := tagModel.GetTagAll(10)
	pageResult["tags"] = tags

	pageResult["title"] = keyword + "_全栈工匠"
	pageResult["keywords"] = "全栈开发，系统架构，后端博客，前端博客，后端框架，前端框架，PHP，Java，C#，Golang，Python，Vue，Html，Javascript，CSS"
	pageResult["description"] = "一个专注于分享全栈以及系统架构技术和趋势的博客"
	pageResult["site"] = "zhongxc.cc"
	pageResult["pvCount"] = s.GetPv()
	pageResult["likeCount"] = articleModel.GetLikeCount()

	// 渲染模板
	c.HTML(http.StatusOK, "search.tmpl", pageResult)
}

// Search 查看更多文章
func (s *SearchController) Search(c *gin.Context) {
	sort := c.DefaultQuery("sort", "")
	p := c.DefaultQuery("page", "1")
	ps := c.DefaultQuery("pageSize", "10")
	keyword := c.DefaultQuery("keyword", "")
	keywordEscape := s.ReplaceSpecifiedChar(keyword)

	page, err := strconv.ParseInt(p, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "页码参数错误"})
	}

	pageSize, err := strconv.ParseInt(ps, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "每页显示条数参数错误"})
	}

	pageResult := articleModel.GetArticlePage(page, pageSize, keywordEscape, "", "", sort)

	c.JSON(http.StatusOK, pageResult)
}
